package com.example.jwt.config;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.io.IORuntimeException;
import com.alibaba.fastjson.JSON;
import com.example.jwt.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: mtl
 * @Date: 2022/1/17 16:55
 * @Description: 过滤器
 */
@Configuration
@Slf4j
public class Interceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        StringBuffer path = request.getRequestURL();
        int login = path.indexOf("login");
        if(login>0){
            log.info("------------------- 属于登录接口 -------------------");
            return true;
        }
        String token = request.getHeader("token") == null ? request.getParameter("token") : request.getHeader("token");
        if(StringUtils.isEmpty(token)){
            WebMvcConfig.writer("请登录",response);
            log.error("------------------- 用户未登录 请登陆后再访问接口 -------------------");
            return false;
        }
        log.info("-----------------------执行i前置处理器------ 这里返回true 才能通过----------------------");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("-----------------------执行后置处理器----------------------------");


    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("-----------------------完成返回结果处理器----------------------------");


    }
}
